const readline = require('readline');
const { calculateEntropy } = require('./entropy');
const { validateProbability, validateProbabilitiesSum } = require('./inputValidator');

// 初始化读取输入的函数
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let probabilities = [];

// 验证并计算熵的主逻辑
function validateAndCalculateEntropy() {
    const validation = validateProbabilitiesSum(probabilities);

    if (!validation.isValid) {
        console.log(validation.message);
        probabilities = [];
        promptInput(); // 重新开始交互输入
    } else {
        console.log(`p = [${probabilities.join(", ")}]`);
        const entropy = calculateEntropy(probabilities);
        console.log(`h(p) = ${entropy.toFixed(3)} bit`);
        rl.close();
    }
}

// 交互式输入概率的函数，验证每个输入
function promptInput() {
    rl.question(`请输入p${probabilities.length}: `, (input) => {
        if (input.trim() === '') {  // 检测到Ctrl+D结束
            const validation = validateProbabilitiesSum(probabilities);
            if (!validation.isValid) {
                console.log(validation.message);
                probabilities = [];
                promptInput(); // 重新开始交互输入
            } else if (probabilities.length >= 2) {
                validateAndCalculateEntropy(); // 如果已有两个以上的概率，计算熵
            } else {
                console.log("命令行参数错误：概率数据少于两个！");
                promptInput();
            }
        } else {
            const value = parseFloat(input);
            const validation = validateProbability(value);
            
            if (!validation.isValid) {
                console.log(validation.message);
                promptInput(); // 重新输入当前概率
            } else {
                probabilities.push(value);
                
                const sum = probabilities.reduce((acc, prob) => acc + prob, 0);
                if (sum >= 1) {
                    validateAndCalculateEntropy(); // 如果概率和达到或超过1，计算熵
                } else {
                    if (probabilities.length >= 2) {
                        console.log("按Ctrl+D结束输入并计算熵");
                    }
                    promptInput(); // 继续输入下一个概率
                }
            }
        }
    });
}

// 处理命令行参数输入的逻辑
function handleCommandLineArgs(args) {
    const isCommaSeparated = args[0].includes(',');
    const isSpaceSeparated = args.every(arg => !arg.includes(','));

    if (isCommaSeparated && isSpaceSeparated) {
        console.log("输入的概率数据格式错误，不能同时使用逗号和空格分隔");
        console.log("请输入信源概率分布：（Ctrl+D退出输入）");
        promptInput();
        return;
    }

    // 处理逗号分隔
    if (isCommaSeparated) {
        probabilities = args[0].split(',').map(Number);
    } else if (isSpaceSeparated) {
        probabilities = args.map(Number);
    }

    // 验证命令行输入的概率是否合法
    const validation = validateProbabilitiesSum(probabilities);
    if (!validation.isValid) {
        console.log(validation.message);
        probabilities = [];
        promptInput();
    } else {
        validateAndCalculateEntropy();
    }
}

// 主流程
if (process.argv.length > 2) {
    const args = process.argv.slice(2);
    handleCommandLineArgs(args); // 命令行参数存在时，处理命令行输入
} else {
    console.log("请输入信源概率分布：（Ctrl+D退出输入）");
    promptInput(); // 无命令行参数时，进入交互输入模式
}






